package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    //统计指定区间内的营业额
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        String joindate = getJoinDate(begin,end,dateList);

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            Double sum = orderMapper.countAmountByDate(date, Orders.COMPLETED);
            turnoverList.add(sum==null?0:sum);
        }

        String jointurnover = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO
                .builder()
                .dateList(joindate)
                .turnoverList(jointurnover)
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取日期
        List<LocalDate> dateList = new ArrayList<>();
        String joindate = getJoinDate(begin,end,dateList);

        //获取每天的新增用户数量(就是类似PDD那种新用户)
        List<Integer> newUserList = new ArrayList<>();
        //获取每天的总用户数量(就是总共注册过多少用户)
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //createTime为当天的即为新用户
            Integer newUserNum = userMapper.countNewUser(date);
            //createTime小于等于当天的即为总用户
            Integer totalUserNum = userMapper.countTotalUser(date);

            newUserList.add(newUserNum==null?0:newUserNum);
            totalUserList.add(totalUserNum==null?0:totalUserNum);
        }

        String joinnewuser = StringUtils.join(newUserList, ",");
        String jointotaluser = StringUtils.join(totalUserList, ",");
        return UserReportVO
                .builder()
                .dateList(joindate)
                .newUserList(joinnewuser)
                .totalUserList(jointotaluser)
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //日期列表
        List<LocalDate> dateList = new ArrayList<>();
        String joindate = getJoinDate(begin,end,dateList);

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        int totalOrderCount = 0;
        int validOrderCount = 0;
        for (LocalDate date : dateList) {
            //订单总数及列表
            Integer ordercount = orderMapper.countTotalOrdersByDate(date);
            ordercount = ordercount==null?0:ordercount;
            //把当天的订单数加到总数中
            totalOrderCount+=ordercount;
            //把当天的订单数加入到订单总数列表中
            orderCountList.add(ordercount);

            //有效订单数及列表
            Integer validcount = orderMapper.countValidOrdersByDateAndStatus(date,Orders.COMPLETED);
            validcount = validcount==null?0:validcount;
            //把当天的有效订单数加到有效总数中
            validOrderCount+=validcount;
            //把当天的有效订单数加入到有效订单总数列表中
            validOrderCountList.add(validcount);
        }
        //计算订单完成率
        double orderCompletionRate = (double) validOrderCount/totalOrderCount;
        String jointotal = StringUtils.join(orderCountList, ",");
        String joinvalid = StringUtils.join(validOrderCountList, ",");

        return OrderReportVO
                .builder()
                .dateList(joindate)
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(jointotal)
                .totalOrderCount(totalOrderCount)
                .validOrderCountList(joinvalid)
                .validOrderCount(validOrderCount)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        for (GoodsSalesDTO salesDTO : salesTop10) {
            String name = salesDTO.getName();
            Integer number = salesDTO.getNumber();
            nameList.add(name);
            numberList.add(number);
        }
        String joinname = StringUtils.join(nameList, ",");
        String joinnumber = StringUtils.join(numberList, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(joinname)
                .numberList(joinnumber)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据库，获取运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN),
                LocalDateTime.of(dateEnd, LocalTime.MAX));

        //利用POI将数据写入文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充数据--时间
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获取第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获取第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for(int i = 0;i<30;i++){
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(i+7);
                //日期
                row.getCell(1).setCellValue(date.toString());
                //营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //有效订单
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                //订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //平均客单价
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                //新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());

            }

            //利用输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);



            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    public String getJoinDate(LocalDate begin, LocalDate end,List<LocalDate> dateList){

        while(!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        //org.apache.common.lang3包下的StringUtils工具类
        return StringUtils.join(dateList, ",");
    }
}
